package com.example.studyroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.studyroom.dto.User.UserInfoDTO;
import com.example.studyroom.mapper.UserMapper;
import com.example.studyroom.Entity.User;
import com.example.studyroom.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper; // 注入UserMapper依赖

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User findByUserLogin(String uname, String upass) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUname, uname)
                .eq(User::getUpass, upass);

        return getOne(queryWrapper);
    }

    @Override
    public void registerUser(User user) {
        save(user);
    }

    @Override
    public boolean usernameExists(String username) {
        return count(lambdaQuery().eq(User::getUname, username)) > 0;
    }

    @Override
    public List<User> getAllUsers() {
        return list();
    }

    @Override
    public void deleteUser(Integer uid) {
        removeById(uid);
    }

    @Override
    public void modifyPass(User user) {
        updateById(user);
    }

    @Override
    public List<UserInfoDTO> getUserInfo(String uname) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUname, uname);

        List<User> users = list(queryWrapper);
        return users.stream()
                .map(user -> {
                    UserInfoDTO userInfoDTO = new UserInfoDTO();
                    BeanUtils.copyProperties(user, userInfoDTO);
                    return userInfoDTO;
                })
                .collect(Collectors.toList());
    }



    @Override
    public void modifyUserInfo(User user) {
        // 使用 MyBatis-Plus 自动生成的方法进行更新
        userMapper.updateById(user);
    }

    @Override
    public User findById(Long userId) {
        return getById(userId);
    }
}
